package uz.rt.dicom.data.element;

import uz.rt.dicom.Padding;
import uz.rt.dicom.ValueRepresentation;
import uz.rt.dicom.data.ComparableList;
import uz.rt.dicom.data.StringElement;
import uz.rt.dicom.io.DicomIOException;
import uz.rt.dicom.io.DicomInputStream;
import uz.rt.dicom.tag.DicomTag;

import java.io.IOException;

public class ShortText extends StringElement implements Comparable<ShortText>
{
// --------------------------- CONSTRUCTORS ---------------------------

    public ShortText(DicomTag tag)
    {
        super(tag);
        setMaxLength(1024);
        setPadding(Padding.SPACE);
    }

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Comparable ---------------------

    /**
     * The function compares only the following parameters in order:
     * <ul>
     * <li>Dicom tag</li>
     * <li>Value multiplicity</li>
     * <li>Comparable list of data fields</li>
     * </ul>
     *
     * @param o ShortText
     * @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
     *         the specified object.
     */
    public int compareTo(ShortText o)
    {
        if (!tag.equals(o.getTag())) return tag.compareTo(o.getTag());
        if (!vm.equals(o.getVm())) return vm.compareTo(o.getVm());
        return value.compareTo(o.getValue());
    }

// --------------------- Interface IDataElement ---------------------

    @Override
    public byte[] getVR()
    {
        return ValueRepresentation.ST;
    }

    @Override
    public ValueRepresentation getValueRepresentation()
    {
        return ValueRepresentation.ShortText;
    }

    public void read(DicomInputStream dicomInputStream, int length) throws IOException
    {
        value = null;
        value = new ComparableList<String>();
        String s = dicomInputStream.readString(length, getCharacterSet());
        String[] groups = splitValues(s);
        if (groups.length < vm.getMin() || groups.length > vm.getMax())
        {
            value = null;
            throw new DicomIOException(
                    "Value multiplicity violation: group length = " + groups.length +
                            ", limits are [" + vm.toString() + "]");
        }
        for (String group : groups)
        {
            char c;
            for (int i = 0; i < group.length(); i++)
            {
                c = group.charAt(i);
                if (c == '\\')
                {
                    value = null;
                    throw new DicomIOException(
                            "Backslash characters are not allowed in an LongText object.");
                }
            }
            while (group.endsWith(" ") && group.length() > 0)
            {
                group = group.substring(0, group.length() - 1);
            }
            value.add(group);
        }
    }
}
